<?php

class Instructor {

	function __construct($id) {
		$query = mysql_query("SELECT * FROM `instructor` WHERE `id` = '$id';") or die(mysql_error());
		$result = mysql_fetch_object($query);
		if($result != '') {
			$this->id = $result->id;
			$this->full_name = $result->full_name;
			$this->email = $result->email;
			$this->permission = $result->permission;
		}
	}

	private function updateInstructor() {
		$query = mysql_query("UPDATE `instructor` SET `full_name` = '$this->full_name', `email` = '$this->email', `permission` = '$this->permissiom'") or die(mysql_error());
		return true;
	}
	
	public function setData($full_name,$email) {
		$this->full_name = $full_name;
		$this->email = $email;
		if($this->updateInstructor())
			return true;
		else
			return false;
	}
	
	public function getAllCourses() {
		$courses = null;
		$query = mysql_query("SELECT * FROM `course` WHERE `owner_id` LIKE '%$this->id%'") or die(mysql_error());
		while($r = mysql_fetch_object($query)) {
			$courses[] = new Course($r->id);
		}
		return $courses;
	}

function getAllSurveys($id){
		$this->id = $id;
		$query = mysql_query("SELECT * FROM  `survey` WHERE `instructor_id` = '$id'") or die (mysql_error);
		while($s = mysql_fetch_object($query)){
			$surveys[] = new Survey($s->id);
		}
		if($surveys){
		return $surveys;
		}else{
			return false;
		}
	}
	
	public function getCourse($id) {
		$courses = $this->getAllCourses();
		foreach($courses as $c) {
			if($id == $c->id)
				$course = $c;
		}
		if($course)
			return $course;
		else
			return false;
	}
	
	public function getGroup($id) {
		$courses = $this->getAllCourses();
		if($courses) {
			foreach($courses as $c) {
				$groups = $c->getAllGroups();
				if($groups) {
					foreach($groups as $g) {
						if($g->id == $id) {
							return new Group($id);
						}
					}
				}
			}
		}
	}

	public function addCourse($data) {
		$query = mysql_query("INSERT INTO `course` VALUES (NULL, $this->id , '$data->title', '$data->term', '$data->description')") or die(mysql_error());
		$all = $this->getAllCourses();
		foreach($all as $a) {
			if($a->term == $data->term) {
				$course = $a;
			}
		}
		return $course->id;
	}

	public function removeCourse($id) {
		$all = $this->getAllCourses();
		foreach($all as $a) {
			if($a->id == $id) {
				$a->removeOwner($this->id);
				break;
			}
		}
		return true;
	}

	public function shareCourse($course_id,$instructor_id) {
		$share = new Instructor($instructor_id);
		$course = getCourse($course_id);
		if($course && $share) {
			$course->addOwner($share);
			return true;
		} else
			return false;
	}
}